#!/bin/bash

#ENV
basepath=$(cd `dirname $0`; pwd)
echo "base path:${basepath}"
workpath=${1:-${basepath}}
echo "workspace: ${workpath}"


workDir="${workpath}/work"

#config nginx
confDir="${workDir}/ui-nginx-conf"
echo "conf: ${confDir}"
upstreamFile="${confDir}/conf.d/upstream.conf"
port=91
name="cus_nginx"
prefix_api="cus.api"
prefix_ui="cus_ui"

#generate server names
webServerCount=${2:-2}
servers=""
index=0
while(( $index<${webServerCount} ))
do
	servers="${servers} ${prefix_ui}${index} "
        let "index++"
done

#generate upstream configuration
upstream="upstream webui { 
	#ip_hash;"
for server in ${servers}; do
	upstream="${upstream}
	server ${server}:8006;"
done
upstream="${upstream} 
}"
echo "${upstream}"
echo "${upstream}" > ${upstreamFile}

#generate links for docker command
links=""
for server in ${servers}; do
	links="${links} --link ${server}:${server}"
done
echo ${links}

docker stop ${name}
docker rm ${name}
docker run -idt ${links} --name ${name} -v ${confDir}:/etc/nginx -p ${port}:80 nginx

